package com.perritosca.webservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class RestClient {

	private static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}


	/* This is a test function which will connects to a given
	 * rest service and prints it's response to Android Log with
	 * labels "Praeda".
	 */
	public static JSONArray get(String url)
	{
		JSONArray json = null;
		HttpClient httpclient = new DefaultHttpClient();


		// Prepare a request object
		HttpGet httpget = new HttpGet(url); 

		// Execute the request
		HttpResponse response;
		try {
			response = httpclient.execute(httpget);
			// Examine the response status
			Log.i("JSON STATUS",response.getStatusLine().toString());

			// Get hold of the response entity
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			// to worry about connection release

			if (entity != null) {

				// A Simple JSON Response Read
				InputStream instream = entity.getContent();
				String result= convertStreamToString(instream);
				//Log.i("JSON RESULT",result);

				// A Simple JSONObject Creation
				json = new JSONArray(result);

				// Closing the input stream will trigger connection release
				instream.close();
			}


		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}

		return json;
	}

	public static JSONArray post(String url, String[] values, String[] params)
	{
		JSONArray json = null;
		HttpClient httpclient = new DefaultHttpClient();


		// Prepare a request object
		HttpPost httppost = new HttpPost(url); 

		// Execute the request
		HttpResponse response;
		try {
			// Add your data        
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(params.length);
			for (int i=0; i< params.length; i++){
				nameValuePairs.add(new BasicNameValuePair(values[i], params[i]));        
			}
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
			response = httpclient.execute(httppost);
			// Examine the response status
			Log.i("JSON STATUS",response.getStatusLine().toString());

			// Get hold of the response entity
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			// to worry about connection release

			if (entity != null) {

				// A Simple JSON Response Read
				InputStream instream = entity.getContent();
				String result= convertStreamToString(instream);
				//Log.i("JSON RESULT",result);

				// A Simple JSONObject Creation
				json = new JSONArray(result);

				// Closing the input stream will trigger connection release
				instream.close();
			}


		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}

		return json;
	}
	
	public static JSONObject sendJson(final String url, final String[] values, final Object[] params) { 
        HttpClient client = new DefaultHttpClient(); 
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
        HttpResponse response;
        JSONObject json = new JSONObject(); 
        JSONObject jsonar = null;
        try{ 
            HttpPost post = new HttpPost(url); 
            
            //Construimos llamada con parametros
            for (int i=0; i< params.length; i++){ 
				json.put(values[i], params[i]); 
			}
            StringEntity se = new StringEntity(json.toString());   
            
            //Envio datos
            post.setEntity(se); 
            response = client.execute(post);  
            
            Log.i("JSON STATUS",response.getStatusLine().toString());

			// Get hold of the response entity
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			// to worry about connection release

			if (entity != null) {

				// A Simple JSON Response Read
				InputStream instream = entity.getContent();
				String result= convertStreamToString(instream);
				//Log.i("JSON RESULT",result);

				// A Simple JSONObject Creation
				jsonar = new JSONObject(result);

				// Closing the input stream will trigger connection release
				instream.close();
			}
        } 
        catch(Exception e){ 
            e.printStackTrace(); 
        } 	
        return jsonar;
	} 
	
	public static JSONObject sendJson(final String url, final String strjson) { 
        HttpClient client = new DefaultHttpClient(); 
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
        HttpResponse response; 
        JSONObject jsonar = null;
        try{ 
            HttpPost post = new HttpPost(url); 
            
            StringEntity se = new StringEntity(strjson);   
            
            //Envio datos
            post.setEntity(se); 
            response = client.execute(post);  
            
            Log.i("JSON STATUS",response.getStatusLine().toString());

			// Get hold of the response entity
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			// to worry about connection release

			if (entity != null) {

				// A Simple JSON Response Read
				InputStream instream = entity.getContent();
				String result= convertStreamToString(instream);
				//Log.i("JSON RESULT",result);

				// A Simple JSONObject Creation
				jsonar = new JSONObject(result);

				// Closing the input stream will trigger connection release
				instream.close();
			}
        } 
        catch(Exception e){ 
            e.printStackTrace(); 
        } 	
        return jsonar;
	} 

}
